﻿using System;
using System.Diagnostics;
using FytSoa.Common.EnumHelper;
using Microsoft.AspNetCore.Mvc.Filters;
using FytSoa.Model.Sys;
using FytSoa.Common;
using FytSoa.Common.Extensions;
using FytSoa.Common.AutofacManager;
using FytSoa.Application.Sys;

namespace FytSoa.Application.Authorize
{
    /// <summary>
    /// 日志收集器
    /// </summary>
    public class LogAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 操作类型CRUD
        /// </summary>
        public LogEnum LogType { get; set; }

        /// <summary>
        /// 0=登录  1=操作
        /// </summary>
        public int LogOption { get; set; } = 1;

        /// <summary>
        /// 参数
        /// </summary>
        private string ActionArguments { get; set; }

        /// <summary>
        /// 实行计时器
        /// </summary>
        private Stopwatch Stopwatch { get; set; }

        public LogAttribute()
        {
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
            Stopwatch.Stop();

            var url = context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
            var method = context.HttpContext.Request.Method;

            var qs = ActionArguments;

            var function = context.ActionDescriptor.RouteValues["action"];

            var str = $"\n 方法：{function} \n " +
                $"Url地址：{url} \n " +
                $"请求方式：{method} \n " +
                $"参数：{qs}\n " +
                //$"结果：{res}\n " +
                $"耗时：{Stopwatch.Elapsed.TotalMilliseconds} 毫秒";

            var log = new SysLog()
            {
                Id = Unique.Id(),
                LogType = LogOption,
                Module = context.ActionDescriptor.RouteValues["controller"],
                OperateType = LogType.GetEnumText(),
                Method = function,
                Browser= context.HttpContext.Request.Headers["User-Agent"],
                OperateUser = "admins",
                IP = Utils.GetIp(),
                Address = url,
                Message = str
            };
            var _logService=ServiceLocator.GetService<ISysLogService>();
            _logService.Add(log);
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);
            Stopwatch = new Stopwatch();
            Stopwatch.Start();
        }
    }
}
